package predict.app.music;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MusicMain extends AppCompatActivity {

    //上一首下一首开始，暂停按钮
    private ImageButton button_prev;
    private ImageButton button_play;
    private ImageButton button_stop;
    private ImageButton button_next;
    // 显示歌曲列表
    private ListView list;

    // 歌曲列表对象
    private ArrayList<Music> musicArrayList;

    // 当前歌曲的序号，下标从0开始
    private int number = 0;

    // 播放状态
    private int status;

    // 广播接收器
    private StatusChangedReceiver receiver;

    // 获取布局的根元素
    private LinearLayout root_Layout;

    // 进度条相关
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;
    // 当前歌曲的持续时间和当前位置
    private int duration = 0;
    private int time = 0;
    // 进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    // 播放器模式常量
    private static final int MODE_LIST_SEQUENCE = 0;
    private static final int MODE_SINGLE_CYCLE = 1;
    private static final int MODE_LIST_CYCLE = 2;
    private int playmode;

    // 退出判断标记
    private static boolean isExit = false;

    // 音量控制
    private TextView tv_vol;
    private SeekBar seekbar_vol;

    // 睡眠模式相关组件，标识常量
    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP = false;
    private static final boolean ISSLEEP = true;
    // 默认睡眠时间
    private int sleepminute = 20;
    // 标记是否打开睡眠模式
    private static boolean sleepmode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_main);

        // getSupportActionBar().hide(); //去掉标题栏
        MusicMain.this.setTitle("音乐播放器");  // 修改title

        button_prev = (ImageButton)findViewById(R.id.prev);
        button_play = (ImageButton)findViewById(R.id.play);
        button_stop = (ImageButton)findViewById(R.id.stop);
        button_next = (ImageButton)findViewById(R.id.next);
        list = (ListView)findViewById(R.id.list);
        root_Layout = (LinearLayout)findViewById(R.id.activity_music_main);
        text_Current = (TextView)findViewById(R.id.startTime);
        text_Duration = (TextView)findViewById(R.id.endTime);
        seekBar = (SeekBar)findViewById(R.id.seekBar1);
        textView = (TextView)findViewById(R.id.musicName);
        tv_vol = (TextView)findViewById(R.id.main_tv_volumeText);
        seekbar_vol = (SeekBar)findViewById(R.id.main_sb_volumebar);
        iv_sleep = (ImageView)findViewById(R.id.main_iv_sleep);

        button_prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //moveNumberToPrevious();
                //button_play.setImageResource(R.mipmap.pause);
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
            }
        });
        button_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //if (player != null && player.isPlaying()) {
                //    pause();
                //    button_play.setImageResource(R.mipmap.play);
                //} else {
                //    play(number);
                //    button_play.setImageResource(R.mipmap.pause);
                //}
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
            }
        });
        button_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //stop();
                //button_play.setImageResource(R.mipmap.play);
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        button_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //moveNumberToNext();
                //button_play.setImageResource(R.mipmap.pause);
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //number = position;
                //play(number);
                //button_play.setImageResource(R.mipmap.pause);
                //view.setBackgroundColor(Color.parseColor("#55FF4081"));
                //list.getSelectedView().setBackgroundColor(Color.parseColor("#55FF4081"));
                //System.out.println(list.getSelectedItem());
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (status != MusicService.STATUS_STOPPED) {
                    time = seekBar.getProgress();
                    // 更新文本
                    text_Current.setText(formatTime(time));
                    // 发送广播给MUsicservice，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if (status == MusicService.STATUS_PLAYING) {
                    // 发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    // 进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
                if (status == MusicService.STATUS_PAUSED) {
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
            }
        });

        initMusicList();  // 初始化音乐列表对象函数
        initListView();  // 设置设配器并初始化listView
        initseekBarHandler();  //进度条初始化
        checkMusicFile();  // 如果列表没有歌曲，则播放按钮不可用，并提醒用户
        bindStatusChangedReceiver();  // 绑定广播接收器，可以接收广播
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;
        playmode = MusicMain.MODE_LIST_SEQUENCE;   // 默认播放模式是顺序播放
        sleepmode = MusicMain.NOTSLEEP;    // 默认睡眠模式为关闭状态
    }

    // 绑定广播接收器
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    public void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    }, null, null, MediaStore.Audio.AudioColumns.TITLE);

            if (mMusicCursor != null) {
                // 标题
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                // 艺术家
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                // 总时长
                int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                // 路径
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

                // 通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中
                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                    String strPath = mMusicCursor.getString(indexPath);

                    if (strArtist.equals("<unknown>")) {
                        strArtist = "无艺术家";
                    }
                    Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(music);
                }
            }
        }
    }

    public void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {  // 增强for循环，冒号类似与in的那种循环
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[] { "musicName", "musicArtist" };
        int[] to = { R.id.list_title, R.id.list_artist };

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }

    public void checkMusicFile() {
        if (musicArrayList.isEmpty()) {
            button_prev.setEnabled(false);
            button_play.setEnabled(false);
            button_stop.setEnabled(false);
            button_next.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            button_prev.setEnabled(true);
            button_play.setEnabled(true);
            button_stop.setEnabled(true);
            button_next.setEnabled(true);
        }
    }

    // 发送命令，控制音乐播放。参数定义在MusicService类中
    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time", time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    // 内部类，用于播放器状态更新的接收广播
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            String musicName = intent.getStringExtra("musicName");
            String musicAritist = intent.getStringExtra("musicAritist");
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    //list.setSelectionFromTop(number, 0);
                    //list.setSelection(number);
                    list.setSelector(R.color.colorAccent);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    text_Duration.setText(formatTime(duration));
                    button_play.setImageResource(R.mipmap.pause);
                    //设置textview文字，提示已经播放的歌曲
                    MusicMain.this.setTitle("正在播放:" + musicName + " - " + musicAritist);
                    textView.setText("正在播放:" + musicName + " - " + musicAritist);
                    break;
                case MusicService.STATUS_PAUSED:
                    // 停止播放
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    button_play.setImageResource(R.mipmap.play);
                    MusicMain.this.setTitle("已暂停：" + musicName + " - " + musicAritist);
                    textView.setText("已暂停：" + musicName + " - " + musicAritist);
                    break;
                case MusicService.STATUS_STOPPED:
                    // 暂停播放
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MusicMain.this.setTitle("当前没有音乐正在播放");
                    textView.setText("当前没有音乐正在播放");
                    //MainActivity.this.setTitle("GracePlayer");
                    button_play.setImageResource(R.mipmap.play);
                    break;
                /*
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if (number == MusicList.getMusicList().size() - 1)
                        sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                    else
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MusicMain.this.setTitle("音乐播放器");
                    textView.setText("");
                    //MainActivity.this.setTitle("GracePlayer");
                    button_play.setImageResource(R.mipmap.play);
                    break;
                */
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    // 顺序播放
                    if (playmode == MusicMain.MODE_LIST_SEQUENCE) {
                        if (number == MusicList.getMusicList().size() - 1)
                            sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    } else if (playmode == MusicMain.MODE_SINGLE_CYCLE)   //单曲循环
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    else if (playmode == MusicMain.MODE_LIST_CYCLE) {//列表循环
                        if (number == MusicList.getMusicList().size() - 1) {
                            number = 0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        } else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MusicMain.this.setTitle("");
                    button_play.setImageResource(R.mipmap.play);
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    // 媒体播放类
    private MediaPlayer player = new MediaPlayer();

    // 读取音乐文件
    public void load (int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getMusicPath());
            player.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 播放音乐
    private void play (int number) {
        // 停止当前播放
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
    }

    // 暂停音乐
    private void pause() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

    // 停止柏藩
    private void stop() {
        player.stop();
    }

    // 恢复播放（暂停之后）
    private void resume() {
        player.start();
    }

    // 重新播放（播放完成之后）
    private void replay() {
        player.start();
    }

    // 下一首
    private void moveNumberToNext() {
        // 判断是否到达列表低端
        if (number == MusicList.getMusicList().size() - 1) {
            Toast.makeText(MusicMain.this, R.string.arrival_bottom, Toast.LENGTH_SHORT).show();
        } else {
            play(++number);
        }
    }

    // 上一首
    private void moveNumberToPrevious() {
        // 判断是否到达列表顶端
        if (number == 0) {
            Toast.makeText(MusicMain.this, R.string.arrival_top, Toast.LENGTH_SHORT).show();
        } else {
            play(--number);
        }
    }

    // 设置Activity的主题，包括修改背景图片等等
    private void setTheme(String theme) {
        if("主题1".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_color);
        } else if("主题2".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_digit_flower);
        } else if("主题3".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_mountain);
        } else if("主题4".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_running_dog);
        } else if("主题5".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_snow);
        } else if("主题6".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_music_girl);
        } else if("主题7".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.mipmap.bg_blur);
        }
    }

    // 创建菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    // 处理菜单点击事件,菜单栏
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            //显示列表对话框
            case R.id.menu_theme:
                new AlertDialog.Builder(this)
                        .setTitle("请选择主题")
                        .setItems(R.array.theme,
                                new DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // 获取在array.xml定义的主题名称
                                        String theme = PropertyBean.THEMES[which];
                                        // 设置Activity的主题
                                        setTheme(theme);
                                        // 保存选择的主题
                                        PropertyBean propetry = new PropertyBean(MusicMain.this);
                                        propetry.setAndSaveTheme(theme);

                                    }
                                }).show();
                break;
            case R.id.menu_about:
                //显示文本对话框
                new AlertDialog.Builder(MusicMain.this).setTitle("GracePlayer")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                new AlertDialog.Builder(MusicMain.this).setTitle("提示")
                        .setMessage(R.string.quit_message).setPositiveButton("确定",new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消",  new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
            case R.id.menu_playmode:
                String[] mode = new String[] {"顺序播放", "单曲循环", "列表循环"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MusicMain.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode, //设置单选项，第二个参数是默认选择的序号，这里根据playmode的值来确定
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                playmode = arg1;
                            }
                        } );
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                switch (playmode) {
                                    case 0:
                                        playmode = MusicMain.MODE_LIST_SEQUENCE;
                                        Toast.makeText(getApplicationContext(), R.string.sequence, Toast.LENGTH_SHORT).show();
                                        break;
                                    case 1:
                                        playmode = MusicMain.MODE_SINGLE_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.singlecycle, Toast.LENGTH_SHORT).show();
                                        break;
                                    case 2:
                                        playmode = MusicMain.MODE_LIST_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                builder.create().show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showSleepDialog() {
        // 先用getLayoutInflater().inflate方法获取布局，用来初始化一个View类对象
        final View userview = this.getLayoutInflater().inflate(R.layout.dialog, null);
        // 通过view类的findViewById方法获取到组件对象
        final TextView tv_minute = (TextView)userview.findViewById(R.id.dialog_tv);
        final Switch switch1 = (Switch)userview.findViewById(R.id.dialog_switch);
        final SeekBar seekbar = (SeekBar)userview.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于：" + sleepminute + "分钟");
        // 根据当前的睡眠状态来确定Switch的状态
        if (sleepmode == MusicMain.ISSLEEP) switch1.setChecked(true);
        seekbar.setMax(60);
        seekbar.setProgress(sleepminute);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepminute = progress;
                tv_minute.setText("睡眠于：" + sleepminute + "分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepmode = isChecked;
            }
        });
        // 定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };
        // 定义对话框一级初始化
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0 ~ 60分钟)");
        // 设置布局
        dialog.setView(userview);
        // 设置取消按钮相应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss();
            }
        });
        // 设置重置按钮相应时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepmode == MusicMain.ISSLEEP) {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MusicMain.NOTSLEEP;
                sleepminute = 20;
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        // 设置确定按钮相应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepmode == MusicMain.ISSLEEP) {
                    timer_sleep = new Timer();
                    int time = seekbar.getProgress();
                    // 启动任务，time*60*1000毫秒后执行
                    timer_sleep.schedule(timerTask, time * 60 * 1000);
                } else {
                    // 取消任务
                    timerTask.cancel();
                    if (timer_sleep != null)
                        timer_sleep.cancel();
                    dialog.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }

    // 初始化seekBar
    private void initseekBarHandler () {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    // 毫秒转换为格式“mm：ss”
    public String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    // 音量控制函数
    private void audio_Control() {
        // 获取音量管理器
        final AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
        // 设置当前调整音量大小只是针对媒体音乐
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        // 设置滑动条最大值
        final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setMax(max_progress);
        // 设置当前音量
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setProgress(progress);
        tv_vol.setText("音量：" + (progress*100/max_progress) + "%");
        seekbar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_vol.setText("音量：" + (progress * 100) / (max_progress) + "%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean popetry = new PropertyBean(MusicMain.this);
        String theme = popetry.getTheme();
        setTheme(theme);
        audio_Control();
        //睡眠模式打开时显示图标，关闭时隐藏图标
        if (sleepmode == MusicMain.ISSLEEP)
            iv_sleep.setVisibility(View.VISIBLE);
        else
            iv_sleep.setVisibility(View.INVISIBLE);
    }

    // 双击返回,音量键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekbar_vol.getProgress();
                if (progress != 0)
                    seekbar_vol.setProgress(progress - 1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekbar_vol.getProgress();
                if (progress != seekbar_vol.getMax())
                    seekbar_vol.setProgress(progress + 1);
                return true;
            default:
                break;
        }
        return false;
    }

    // 返回事件
    private void exitByDoubleClick() {
        Timer timer = null;
        if (isExit == false) {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序！", Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);   //2秒后执行run函数内容，如果2秒内没按下返回键，修改isExit的值
        } else {
            System.exit(0);
        }
    }
}























